package com.decade.sp02.item.controller;

import com.decade.sp01.pojo.Item;
import com.decade.sp01.service.ItemService;
import com.decade.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * @Author: decade
 * @Description: 商品控制类
 * @Date: 2021/1/18 13:02
 **/
@Slf4j
@RestController
public class ItemController {

    @Autowired
    private ItemService itemService;

    @Value("${server.port}")
    private int port;

    //获取订单商品列表
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("server.port="+port+", orderId="+orderId);

        //随机延迟
        if(Math.random()<0.9) {
            long t = new Random().nextInt(5000);
            System.out.println("item-service-"+port+" - 暂停 "+t);
            Thread.sleep(t);
        }
        List<Item> items = itemService.getItems(orderId);
        return JsonResult.ok(items).msg("port="+port);
    }

    //减少商品库存
    //RequestBody 完整地接收请求协议体数据
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items) {
        itemService.decreaseNumbers(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }
}
